#include "convert.h"

void BinaryTree2Forest(TreeNode *tree_root, TreeNode *forest_root) {
    TreeNode *node = new TreeNode;
    node->val = tree_root->val;
    node->parent = forest_root;
    forest_root->children.PushBack(node);
    if (tree_root->lrchild.first != nullptr) {
        BinaryTree2Forest(tree_root->lrchild.first, node);
    }
    if (tree_root->lrchild.second != nullptr) {
        BinaryTree2Forest(tree_root->lrchild.second, forest_root);
    }
}

void BinaryTree2Forest(const Tree &tree, Forest &forest) {
    forest.is_binary = false;
    forest.root = new TreeNode;
    forest.root->parent = nullptr;
    if (tree.root == nullptr) {
        return;
    }
    BinaryTree2Forest(tree.root, forest.root);
}

void Forest2BinaryTree(TreeNode *forest_root, TreeNode *tree_root, int pos) {
    if (!forest_root->children.IsEmpty()) {
        TreeNode *node = new TreeNode;
        node->val = forest_root->children[0]->val;
        node->parent = tree_root;
        tree_root->lrchild.first = node;
        Forest2BinaryTree(forest_root->children[0], node, 0);
    }
    else {
        tree_root->lrchild.first = nullptr;
    }
    if (pos + 1 < forest_root->parent->children.Size()) {
        TreeNode *node = new TreeNode;
        node->val = forest_root->parent->children[pos + 1]->val;
        node->parent = tree_root;
        tree_root->lrchild.second = node;
        Forest2BinaryTree(forest_root->parent->children[pos + 1], node, pos + 1);
    }
    else {
        tree_root->lrchild.second = nullptr;
    }
}

void Forest2BinaryTree(const Forest &forest, Tree &tree) {
    tree.is_binary = true;
    if (forest.root->children.IsEmpty()) {
        return;
    }
    tree.root = new TreeNode;
    tree.root->val = forest.root->children[0]->val;
    tree.root->parent = nullptr;
    Forest2BinaryTree(forest.root->children[0], tree.root, 0);
}
